<?php


namespace App\Shuixing\Controllers;

use App\Models\Posts\WxComment;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsImg;
use App\Models\Posts\WxPostsTag;
use App\Models\Posts\WxPostsVideo;
use App\Models\Posts\WxTag;
use App\Models\WxCircle;
use App\Models\WxUser;

class HotController
{

    public function index($limit = 7)
    {

        View()->composer('shuixing/home', function ($view) {
            $view->with(['menu' => 1]);
        });

        //热门标签
        $tags = WxTag::where('tags_state', 0)
            ->orderBy('tags_number', 'desc')
            ->limit(9)->get();

        //热门用户
        $user = WxUser::whereIn('id', [9999, 10000, 10001])
            ->get(['id', 'user_name', 'user_avatar', 'user_introduce']);
        $user->map(function ($v) {
            $v->posts_count = WxPost::where('user_id', $v->id)->count();
        });

        //热门圈子
        $circle = WxCircle::where('circle_state', 1)
            ->where('is_hot', 1)
            ->orderBy('sort', 'asc')
            ->limit(6)->get(['id', 'head_portrait']);

        //及时热榜
        $hot_posts = WxPost::where('is_examine', 1)
            ->where('posts_state', 0)
            ->orderBy('id', 'desc')->limit(3)->get();
        $hot_posts = self::postsParame($hot_posts);//文章详情

        //热榜帖子
        $data = WxPost::where('is_examine', 1)
            ->where('posts_state', 0)
            ->orderBy('is_sticky', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($limit);
        $data = self::postsParame($data);//文章详情

        return view('shuixing/hot', ['data' => $data, 'hot_posts' => $hot_posts, 'tags' => $tags, 'circle' => $circle, 'user' => $user]);
    }

    public static function postsParame($data)
    {
        $data->map(function ($v) {
            $v->user = WxUser::where('id', $v->user_id)
                ->first(['user_avatar', 'user_name', 'id', 'is_member', 'is_official', 'is_authentication']);//发帖人
            $tagsIds = WxPostsTag::where('posts_id', $v->id)->pluck('tags_id');//标签ID列表
            $v->tags = WxTag::whereIn('id', $tagsIds)->get(['tags_name', 'id']);//标签列表
            $v->like_count = WxLike::where('posts_id', $v->id)->count(); // 帖子喜欢数量
            $v->comment_count = WxComment::where(['posts_id' => $v->id, 'comment_state' => 1])->count(); // 评论数量
            $v->image = WxPostsImg::where('posts_id', $v->id)->value('img_url'); // 帖子图片
            $v->vimage = WxPostsVideo::where('posts_id', $v->id)->value('video_thumb_url'); // 帖子视频封面
            $v->format_time = format_datetime($v->created_at); // 发帖时间
        });

        return $data;
    }
}
